package com.apestech.framework.xml.pub.core;

import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import org.dom4j.Element;

import java.util.List;

/**
 * @author hup
 * @create 2018-12-13-9:47
 */
public class NodeJson extends ElementUtil{
    private Element node;
    private JSONObject result;

    public NodeJson(Element node) throws Exception {
        this.node=node;
    }

    public void expain() throws Exception {
        if(result==null) result=new JSONObject();
        result.putAll(getNodeOrderAttr(node));
        List<?> list=node.content();
        int len=list.size();
        for(int i=0; i<len; i++) {
            String scalss = list.get(i).getClass().getName();
            if (scalss.equals("org.dom4j.tree.DefaultElement")) {
                Element eml = (Element) list.get(i);
                String txt=eml.getTextTrim();
                if(txt!=null && !"".equals(txt.trim())){
                    if(eml.content().size()==0){
                        result.put(eml.getName(),txt);
                    } else {
                        result.put(eml.getName()+"_cdata",txt);
                    }
                }
                NodeJson nodejson=new NodeJson(eml);
                nodejson.expain();
                if(nodejson.getResult()!=null){
                    JSONArray nodelist=null;
                    Object obj=result.get(eml.getName());
                    if(obj==null){
                        if(nodejson.getResult().size()==1){
                            String k=nodejson.getResult().getKeylist().get(0);
                            if(nodejson.getResult().get(k) instanceof JSONArray) result.put(eml.getName(),nodejson.getResult().get(k));
                            else result.put(eml.getName(),nodejson.getResult());
                        } else result.put(eml.getName(),nodejson.getResult());
                    }
                    else {
                        if(obj instanceof JSONObject){
                            nodelist=new JSONArray();
                            nodelist.add(obj);
                        } else if(obj instanceof JSONArray){
                            nodelist= (JSONArray) obj;
                        }
                        if(nodelist!=null){
                            nodelist.add(nodejson.getResult());
                            result.put(eml.getName(),nodelist);
                        }
                    }
                }
            }
        }
    }

    public JSONObject getResult() {
        return result;
    }

}
